import router from '@/router';
import axios from 'axios'
import { ElMessage } from 'element-plus'

const service = axios.create({
    // baseURL: 'https://api.sczgss.com/admin/',
    baseURL: 'https://192.168.1.10/admin/',
    // baseURL: '/api',
    timeout: 10000,
    retry: 3, //设置全局重试请求次数（最多重试几次请求）
    retryDelay: 1000, //设置全局请求间隔
})

service.interceptors.request.use(config => {
    const token = sessionStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `bearer${token}`
    }
    return config;
}, error => {
    return Promise.reject(error);
});

service.interceptors.response.use(response => {
    if (response.status >= 200 && response.status < 300) {
        const { code, msg, data } = response.data
        if (code === 200) {
            return { code, data }
        } else if (code == 201) {
            ElMessage.error(msg)
            return code
        } else if (code == 401) {
            sessionStorage.removeItem('token')
            router.push('/login')
        }
    }
    if (response.status == 500) {
        ElMessage.error('后台出错，请稍后')
    }
    return response.data;
}, error => {
    if (error.message == 'timeout of 10000ms exceeded') {
        ElMessage({ type: 'warning', message: '请求超时，请检查网络' })
    } else if (error.message == "Network Error") {
        ElMessage({ type: 'warning', message: '网络连接有误，请检查网络' })
    }
    return
    var config = error.config;
    if (!config || !config.retry) return Promise.reject(error)
    if (error.config.data) {
        // return Promise.reject({ type: "error", msg: error.message });
        if (error.message === "Network Error") {
            return ElMessage({ type: "warning", message: "网络连接有误，请检查网络" });
        } else if (error.message === "timeout of 10000ms exceeded") {
            return ElMessage({ type: "warning", message: "请求超时，请检查网络" });
        }
        // else {
        //     return ElMessage({ type: "error", message: "出现错误，请稍后再试" });
        // }
    }
    config.__retryCount = config.__retryCount || 0;

    if (config.__retryCount >= config.retry) {
        if (error.message === "Network Error") {
            return ElMessage({ type: "warning", message: "网络连接已断开，请检查网络" });
        } else if (error.message === "timeout of 10000ms exceeded") {
            return ElMessage({ type: "warning", message: "请求超时，请检查网络" });
        }
        // else {
        //     return ElMessage({ type: "error", message: "出现错误，请稍后再试" });
        // }
    }
    config.__retryCount += 1;
    var backoff = new Promise(function (resolve) {
        setTimeout(function () {
            resolve();
        }, config.retryDelay || 1);
    });
    return backoff.then(function () {
        return service(config);
    });
});
export default service
